

import com.boot.MainBoot;
import com.service.DepService;
import net.bytebuddy.asm.Advice;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.nio.charset.CoderResult;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest(classes = MainBoot.class)
@RunWith(SpringRunner.class)
class DepServiceText {

    @Autowired
    private DepService depService;

    @Autowired
    private SolrClient solrClient;


    //添加  从pojo通过指定@Field来添加到solr
    @Test
    void addSolr() {
        depService.addSolr();
    }
//    板砖。徒手不出


    /**
     * 查询索引库
     */
    @Test
    public void querySolr(){

        SolrQuery solrQuery=new SolrQuery();

        solrQuery.setQuery("部");

        solrQuery.setStart(0);
        solrQuery.setRows(10);

        solrQuery.set("df","depName");
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("depName");
        solrQuery.setHighlightSimplePre("<span style='color:red'>");
        solrQuery.setHighlightSimplePost("</span>");

        try {

            QueryResponse query = solrClient.query(solrQuery);

            SolrDocumentList results = query.getResults();

            Map<String, Map<String, List<String>>> highlighting = query.getHighlighting();

            for (SolrDocument list:results){

                String itemString = "" ;

                List<String> strings = highlighting.get(list.get("id")).get("depName");

                if(strings!=null && strings.size()>0){
                    itemString=strings.get(0);
                }else{
                    itemString= (String) list.get("depName");
                }

                System.out.println(itemString);
            }

        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除索引库
     */
    @Test
    public void testDeleteDocument() {
        try {
            solrClient.deleteByQuery("*:*");
            solrClient.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}